package com.jctrip.hotel.management.interceptor;

import com.jctrip.hotel.management.util.JwtUtil;
import io.jsonwebtoken.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            throw new RuntimeException("请先登录!");
        }else{
            try {
                JwtParser parser = Jwts.parser();
                //解析token的SigningKey必须和生成token时设置密码一致
                parser.setSigningKey(JwtUtil.generalKey());
                //如果token检验通过（密码正确，有效期内）则正常执行，否则抛出异常
                Jws<Claims> claimsJws = parser.parseClaimsJws(token);
                //true就是验证通过，放行
                return true;
            }catch (ExpiredJwtException e){
                throw new RuntimeException("登录过期，请重新登录!");
            }catch (UnsupportedJwtException e){
                throw new RuntimeException("Token不合法");
            }catch (Exception e){
                throw new RuntimeException("请先登录!");
            }
        }
    }

}
